package com.xpsoft.oa.service.produce.impl;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.reflect.TypeToken;
import com.xpsoft.core.service.impl.BaseServiceImpl;
import com.xpsoft.core.util.JsonUtil;
import com.xpsoft.oa.dao.produce.MaterialPurRealDao;
import com.xpsoft.oa.dao.produce.MaterialPurRealInfoDao;
import com.xpsoft.oa.model.produce.MaterialPurReal;
import com.xpsoft.oa.model.produce.MaterialPurRealInfo;
import com.xpsoft.oa.service.produce.MaterialPurRealService;

public class MaterialPurRealServiceImpl extends BaseServiceImpl<MaterialPurReal> implements MaterialPurRealService{
	private MaterialPurRealDao dao;
	@Autowired
	private MaterialPurRealInfoDao materialPurRealInfoDao;
	
	public MaterialPurRealServiceImpl(MaterialPurRealDao dao) {
		super(dao);
		this.dao=dao;
	}

	@Override
	public void saveMaterialPurReal(MaterialPurReal materialPurReal,
			String dataList) {
		// TODO Auto-generated method stub
		dao.save(materialPurReal);
		Boolean isNew = true;//新增标志
		if(materialPurReal.getId()!=null){
			isNew = false;
		}
		dao.save(materialPurReal);
		if(StringUtils.isNotBlank(dataList)){
			List<MaterialPurRealInfo> materialPurRealInfoList = JsonUtil.fromJsonTypesWithDate(dataList,
					new TypeToken<List<MaterialPurRealInfo>>() {
					}.getType());
			if(!isNew){//修改
				List<Long> idList = new ArrayList<Long>();
				for(MaterialPurRealInfo materialPurRealInfo:materialPurRealInfoList){
					if(materialPurRealInfo.getId()!=null){//修改的记录
						idList.add(materialPurRealInfo.getId());
					}
				}
				if(idList.size()>0){//先进行删除
					materialPurRealInfoDao.deleteMaterialPurRealInfos(materialPurReal.getId(), idList);
				}
			}
			for(MaterialPurRealInfo materialPurRealInfo:materialPurRealInfoList){
				materialPurRealInfo.setMaterialPurReal(materialPurReal);
				materialPurRealInfo.setCreateUser(materialPurReal.getCreateUser());
				materialPurRealInfo.setCreateTime(materialPurReal.getCreateTime());
				materialPurRealInfoDao.save(materialPurRealInfo);
			}
		}
	}

}